package vip.xiaonuo.h5.royalty.modular.station.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vip.xiaonuo.h5.royalty.modular.station.param.FullStationListParam;
import vip.xiaonuo.h5.royalty.modular.station.param.RankStationListParam;

import vip.xiaonuo.h5.royalty.modular.station.service.StationService;
import vip.xiaonuo.h5.royalty.modular.station.vo.*;
import vip.xiaonuo.h5.royalty.system.profitsharerelation.entity.H5ProfitShareRelation;
import vip.xiaonuo.h5.royalty.system.profitsharerelation.service.H5ProfitShareRelationService;
import vip.xiaonuo.h5.royalty.system.station.entity.H5Station;
import vip.xiaonuo.h5.royalty.system.station.service.H5StationService;
import vip.xiaonuo.h5.royalty.system.profitsharestatistics.entity.H5ProfitShareStatistics;
import vip.xiaonuo.h5.royalty.system.profitsharestatistics.service.H5ProfitShareStatisticsService;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 站点服务实现类
 */
@Slf4j
@Service
public class StationServiceImpl implements StationService {

    @Autowired
    private H5ProfitShareRelationService h5ProfitShareRelationService;

    @Autowired
    private H5StationService h5StationService;

    @Autowired
    private H5ProfitShareStatisticsService h5ProfitShareStatisticsService;

    @Override
    public SimpleStationPage getSimpleStationList() {
        String loginUserId = StpUtil.getLoginIdAsString();

        // 查询用户关联的站点关系
        LambdaQueryWrapper<H5ProfitShareRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(H5ProfitShareRelation::getSharePartyId, loginUserId);
        queryWrapper.eq(H5ProfitShareRelation::getStatus, "1"); // 只查询生效的关联关系

        List<H5ProfitShareRelation> relations = h5ProfitShareRelationService.list(queryWrapper);

        SimpleStationPage result = new SimpleStationPage();

        if (ObjUtil.isEmpty(relations)) {
            result.setList(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        List<SimpleStationVo> stationList = new ArrayList<>();
        relations.forEach(relation -> {
            SimpleStationVo simpleStationVo = new SimpleStationVo();
            simpleStationVo.setStationId(relation.getStationId());
            stationList.add(simpleStationVo);
        });

        result.setList(stationList);
        result.setTotal(stationList.size());
        return result;
    }

    @Override
    public FullStationListPage getFullStationList(FullStationListParam param) {
        // 获取当前登录用户ID
        String loginUserId = StpUtil.getLoginIdAsString();

        // 从关联表中查询用户关联的站点关系
        LambdaQueryWrapper<H5ProfitShareRelation> relationWrapper = new LambdaQueryWrapper<>();
        relationWrapper.eq(H5ProfitShareRelation::getSharePartyId, loginUserId);
        relationWrapper.eq(H5ProfitShareRelation::getStatus, "1"); // 只查询生效的关联关系

        List<H5ProfitShareRelation> relations = h5ProfitShareRelationService.list(relationWrapper);

        // 创建返回结果对象
        FullStationListPage result = new FullStationListPage();

        if (ObjUtil.isEmpty(relations)) {
            result.setList(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        // 将关联关系转换为字典，key为站点ID，value为整个关联关系对象
        Map<String, H5ProfitShareRelation> stationRelationMap = relations.stream()
                .collect(Collectors.toMap(
                        H5ProfitShareRelation::getStationId,
                        relation -> relation,
                        // 如果同一个站点有多个关联关系，取第一个
                        (existing, replacement) -> existing
                ));

        // 提取站点ID列表并去重
        List<String> stationIds = new ArrayList<>(stationRelationMap.keySet());

        // 根据站点ID查询站点详细信息，添加分页和筛选条件
        LambdaQueryWrapper<H5Station> stationWrapper = new LambdaQueryWrapper<>();
        stationWrapper.in(H5Station::getId, stationIds);

        // 添加lastId条件（分页）
        if (ObjUtil.isNotEmpty(param.getLastId())) {
            stationWrapper.gt(H5Station::getId, param.getLastId());
        }

        // 添加状态筛选
        if (ObjUtil.isNotEmpty(param.getStatus())) {
            stationWrapper.eq(H5Station::getStatus, param.getStatus());
        }

        // 添加关键词搜索
        if (ObjUtil.isNotEmpty(param.getKeyword())) {
            stationWrapper.and(wrapper -> wrapper
                    .like(H5Station::getName, param.getKeyword()));
        }

        // 按ID升序排序，每次返回10条
        stationWrapper.orderByAsc(H5Station::getId);
        stationWrapper.last("LIMIT 10");

        List<H5Station> stations = h5StationService.list(stationWrapper);

        // 将站点实体转换为VO对象，并设置关联关系信息
        List<FullStationListVo> stationList = stations.stream()
                .map(station -> {
                    FullStationListVo stationVo = new FullStationListVo();
                    stationVo.setStationId(station.getId());
                    stationVo.setStationName(station.getName());
                    stationVo.setStationAddress(station.getAddress());
                    stationVo.setPileCount(station.getPileNumber());
                    stationVo.setStatus(station.getStatus());
                    // 设置默认值,如果有值会在下面被覆盖
                    stationVo.setShareRatio("0%");

                    // 从字典中获取关联关系对象，并设置完整信息
                    H5ProfitShareRelation relation = stationRelationMap.get(station.getId());
                    if (ObjUtil.isNotEmpty(relation)) {

                        // 设置机构ID（运营商ID）
                        stationVo.setOperatorId(relation.getOrgId());

                        // 设置分润比例 - 精确到2位小数，没有小数部分不显示
                        BigDecimal ratio = relation.getShareRatio();
                        String shareRatio = "0%";
                        if (ratio != null) {
                            // 去除末尾的零和小数点（如果没有小数部分）
                            String ratioStr = ratio.stripTrailingZeros().toPlainString();
                            // 如果有小数部分，检查小数位数
                            if (ratioStr.contains(".")) {
                                // 精确到2位小数
                                java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
                                ratioStr = df.format(ratio);
                            }
                            shareRatio = ratioStr + "%";
                        }
                        stationVo.setShareRatio(shareRatio);

                        // 设置开始时间 - 格式化为yyyy-MM-dd
                        if (relation.getStartDate() != null) {
                            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                            stationVo.setStartTime(sdf.format(relation.getStartDate()));
                        }

                        // 设置结束时间 - 格式化为yyyy-MM-dd
                        if (relation.getEndDate() != null) {
                            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                            stationVo.setEndTime(sdf.format(relation.getEndDate()));
                        }

                    }

                    return stationVo;
                })
                .collect(Collectors.toList());

        result.setList(stationList);
        result.setTotal(stationList.size());
        return result;
    }

    @Override
    public RankStationPage getRankStationList(RankStationListParam param) {
        // 1. 获取当前登录用户ID
        String loginUserId = StpUtil.getLoginIdAsString();

        // 2. 构建查询条件
        LambdaQueryWrapper<H5ProfitShareStatistics> queryWrapper = new LambdaQueryWrapper<>();

        // 根据loginId和shareId比对找到这个人
        queryWrapper.eq(H5ProfitShareStatistics::getSharePartyId, loginUserId);

        // 设置日期筛选条件
        if (ObjUtil.isNotEmpty(param.getStartDate()) && ObjUtil.isNotEmpty(param.getEndDate())) {
            try {
                // 将字符串日期转换为Date类型，适配数据库的Date字段
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                Date startDate = sdf.parse(param.getStartDate());
                Date endDate = sdf.parse(param.getEndDate());

                queryWrapper.ge(H5ProfitShareStatistics::getStatisticsDate, startDate)
                            .le(H5ProfitShareStatistics::getStatisticsDate, endDate);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }

        // 3. 查询分润统计数据
        List<H5ProfitShareStatistics> statisticsList = h5ProfitShareStatisticsService.list(queryWrapper);

        // 创建返回结果对象
        RankStationPage result = new RankStationPage();

        if (ObjUtil.isEmpty(statisticsList)) {
            result.setList(new ArrayList<>());
            result.setTotal(0);
            return result;
        }

        // 4. 根据场站分组统计
        Map<String, List<H5ProfitShareStatistics>> stationGroupMap = statisticsList.stream()
                .collect(Collectors.groupingBy(H5ProfitShareStatistics::getStationId));

        // 5. 构建场站排名列表
        List<RankStationVo> rankStationList = new ArrayList<>();

        // 查询所有相关场站信息
        List<String> stationIds = new ArrayList<>(stationGroupMap.keySet());
        LambdaQueryWrapper<H5Station> stationWrapper = new LambdaQueryWrapper<>();
        stationWrapper.in(H5Station::getId, stationIds);
        List<H5Station> stations = h5StationService.list(stationWrapper);

        // 创建场站对象映射 - key为ID，value为完整的H5Station对象
        Map<String, H5Station> stationMap = stations.stream()
                .collect(Collectors.toMap(H5Station::getId, station -> station));

        // 查询用户关联的站点关系
        LambdaQueryWrapper<H5ProfitShareRelation> relationWrapper = new LambdaQueryWrapper<>();
        relationWrapper.eq(H5ProfitShareRelation::getSharePartyId, loginUserId);
        relationWrapper.in(H5ProfitShareRelation::getStationId, stationIds);
        List<H5ProfitShareRelation> relations = h5ProfitShareRelationService.list(relationWrapper);

        // 创建分成关系对象映射 - key为站點ID，value为完整的H5ProfitShareRelation对象
        Map<String, H5ProfitShareRelation> relationMap = relations.stream()
                .collect(Collectors.toMap(
                        H5ProfitShareRelation::getStationId,
                        relation -> relation,
                        (existing, replacement) -> existing
                ));

        // 计算每个场站的汇总数据
        for (Map.Entry<String, List<H5ProfitShareStatistics>> entry : stationGroupMap.entrySet()) {
            String stationId = entry.getKey();
            List<H5ProfitShareStatistics> stationStats = entry.getValue();

            // 累加该场站的所有数据
            BigDecimal totalServiceFee = BigDecimal.ZERO;
            BigDecimal actualIncome = BigDecimal.ZERO;

            for (H5ProfitShareStatistics stat : stationStats) {
                totalServiceFee = totalServiceFee.add(stat.getTotalServiceFee() != null ? stat.getTotalServiceFee() : BigDecimal.ZERO);
                actualIncome = actualIncome.add(stat.getTotalShareAmount() != null ? stat.getTotalShareAmount() : BigDecimal.ZERO);
            }

            // 创建场站排名VO
            RankStationVo rankStationVo = new RankStationVo();
            rankStationVo.setStationId(stationId);
            
            // 从场站对象中获取名称，如果场站不存在则使用默认值
            H5Station station = stationMap.get(stationId);
            rankStationVo.setStationName(station != null ? station.getName() : "未知场站");
            rankStationVo.setTotalServiceFee(totalServiceFee.setScale(2, BigDecimal.ROUND_HALF_UP).toString());

            // 设置分成比例 - 从关系对象中获取
            H5ProfitShareRelation relation = relationMap.get(stationId);
            BigDecimal shareRatio = relation != null ? relation.getShareRatio() : BigDecimal.ZERO;
            String shareRatioStr = "0%";
            if (shareRatio != null && shareRatio.compareTo(BigDecimal.ZERO) > 0) {
                // 去除末尾的零和小数点
                String ratioStr = shareRatio.stripTrailingZeros().toPlainString();
                if (ratioStr.contains(".")) {
                    // 精确到2位小数
                    java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
                    ratioStr = df.format(shareRatio);
                }
                shareRatioStr = ratioStr + "%";
            }
            rankStationVo.setShareRatio(shareRatioStr);

            rankStationVo.setActualIncome(actualIncome.setScale(2, BigDecimal.ROUND_HALF_UP));
            rankStationVo.setOtherFee(BigDecimal.ZERO.setScale(2, BigDecimal.ROUND_HALF_UP));

            rankStationList.add(rankStationVo);
        }

        // 6. 根据实际收入排名（从高到低）
        rankStationList.sort((a, b) -> b.getActualIncome().compareTo(a.getActualIncome()));

        // 7. 设置返回结果
        result.setList(rankStationList);
        result.setTotal(rankStationList.size());

        return result;
    }

}
